<template>
	<div class="padding-across-10" v-loading="loading" element-loading-text="拼命加载中">
		<headerOpreate style="width: 45%;padding: 5px 0" :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
		<!--区域列表-->
		<div class="district-tree">
			<el-tree :show-overflow-tooltip="true" ref="tree" :data="tableData" show-checkbox :props="defaultProps" node-key="DistrictKeyId" :default-expanded-keys="defaultKey" :render-content="renderContent" :check-strictly="true">
			</el-tree>
		</div>
		<!--添加区域弹出框-->
		<el-dialog title="添加区域" v-model="createAreaDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="form" ref="createForm" :model="createForm" :rules="createRules" label-width="80px" label-position="left">
				<el-form-item label="上级区域" prop="parentAreaName" v-show="parentAreaNameShow">
					<el-input v-model="createForm.parentAreaName" disabled></el-input>
				</el-form-item>
				<el-form-item label="区域名" prop="areaName">
					<el-input v-model="createForm.areaName" required></el-input>
				</el-form-item>
				<!-- <el-form-item label="区域类型" v-if="typeShow">
					<el-select v-model="createForm.type" placeholder="请选择区域类型">
						<template v-for="item in areaType">
							<el-option :label="item.description" :value="item.type"></el-option>
						</template>
					</el-select>
				</el-form-item> -->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="createAreaDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmCreateArea('createForm')">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 排序 -->
		<el-dialog title="区域排序" v-model="sortAreaDialog" :show-close="false" :class="[dialog-tiny-width]">
			<div class="color-list">
				<div class="color-item" v-for="area in sortAreas" v-dragging="{ item: area, list: sortAreas, group: 'area'}" :key="area.DistrictKeyId">区域名称：{{area.Name}}
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="sortAreaDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmSortArea">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 重命名 -->
		<el-dialog title="区域编辑" v-model="renameAreaDialog" :show-close="false" :class="[dialog-tiny-width]">
			<el-form id="form" ref="renameDistrictForm" :model="renameDistrictForm" :rules="createRules" label-width="80px" label-position="left">
				<el-form-item label="创建人" prop="creator">
					<el-input v-model="renameDistrictForm.creator" disabled></el-input>
				</el-form-item>
				<el-form-item label="创建时间" prop="time">
					<el-input v-model="renameDistrictForm.time" disabled></el-input>
				</el-form-item>
				<el-form-item label="修改时间" prop="updateTime">
					<el-input v-model="renameDistrictForm.updateTime" disabled></el-input>
				</el-form-item>
				<el-form-item label="区域名" prop="areaName">
					<el-input v-model="renameDistrictForm.areaName" required></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="renameAreaDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmRename('renameDistrictForm')">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 重命名 -->
		<el-dialog title="绑定馆藏地" v-model="locationDialog" :show-close="false" :class="[dialog-large-width]">
			<el-table border style="width: 100%;" @selection-change="handleSelectionChange" :data="locationDatas">
				<el-table-column type="selection" align="center" width="50px"></el-table-column>
				<el-table-column label="名称" align="center" prop="Name"></el-table-column>
				<el-table-column label="创建时间" align="center" prop="CreateTime"></el-table-column>
				<el-table-column label="创建人" align="center" prop="CreateUid"></el-table-column>
				<el-table-column label="更新时间" align="center" prop="UpdateTime"></el-table-column>
			</el-table>
			<div class="block" style="text-align: right; margin-bottom: 10px;padding-top: 2px">
				<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page="currentPage" :page-size="pageSize" :page-sizes="[10,20,30,40,50]" layout="total,sizes, prev, pager, next, jumper" :total="totalSize">
				</el-pagination>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="locationDialog = false">取 消</el-button>
				<el-button type="primary" @click="confirmBindLocation">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import $ from 'jquery'
	import { HttpServer, GloabFun } from '../../../../assets/js/common.js'
	import headerOpreate from '../../../../components/headerOpreate'

	export default {
		components: {
			headerOpreate
		},
		data() {
			return {
				isReload: false,
				loading: false,
				opreateDatas: [{
					show: true,
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_refresh el-icon--left',
					name: '刷新',
					action: 'reloadDatas'
				},
				{
					show: GloabFun.getUid() == 'admin' ? true : false,
					size: "small",
					type: "primary",
					icon: "el-icon-plus el-icon--left",
					name: "添加",
					action: "createArea"
				},
				{
					show: GloabFun.getUid() == 'admin' ? true : false,
					size: "small",
					type: "primary",
					icon: "el-icon-d-caret el-icon--left",
					name: "排序",
					action: "sortArea"
				},
				{
					show: GloabFun.getUid() == 'admin' ? true : false,
					size: "small",
					type: "danger",
					icon: "el-icon-delete2 el-icon--left",
					name: "删除",
					action: "deleteArea"
				}
				],
				defaultProps: {
					children: 'Children',
					label: 'Name',
					id: 'DistrictKeyId'
				},
				locationDatas: [],
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				locationDialog: false,
				multipleSelection: [],
				bindDistrictrInfo: {},
				typeShow: false,
				parentAreaNameShow: false,
				sortNumber: '',
				tableData: [],
				createAreaDialog: false,
				areaType: [],
				defaultKey: [],
				sortAreas: [],
				sortAreaDialog: false,
				createForm: {
					type: '',
					areaName: '',
					level: '',
					parentkeyid: '',
					parentAreaName: ''
				},
				createRules: {
					areaName: [{
						required: true,
						message: "区域名称不能为空",
						trigger: 'blur'
					}],
				},
				renameAreaDialog: false,
				renameDistrictForm: {
					areaName: '',
					time: '',
					updateTime: '',
					creator: '',
					keyid: '',
					sortNumber: ''
				}
			}
		},
		props: {
			templateObj: {
				type: Object,
				default: function() {
					return {};
				}
			}
		},
		methods: {
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},
			renderContent(h, node) {
				// console.log(h)
				if(node.data.Children != null && node.data.Children.length > 0) {
					return h('span', {
						attrs: {
							class: "clearfloat",
							style: 'width:100%;display:inline-block'
						}
					}, [h('i', {
						attrs: {
							class: "el-icon-eleg-arrow_carrot-down_alt2 el-icon--left"
						}
					}),
					node.data.Name,

					h('span', {
						attrs: {
							style: 'float:right;text-align:right;margin-right:60px'
						}
					}, [
					h('el-button', {
						on: {
							click: this.appendit(node.data)
						},
						attrs: {
							type: 'primary',
							size: 'small'
						}
					}, [h('i', {
						attrs: {
							style: 'margin-right:5px;font-size:13px;',
							class: "el-icon-plus el-icon--left"
						}
					}), '添加']),
					h('el-button', {
						on: {
							click: this.editit(node.data)
						},
						attrs: {
							type: 'primary',
							size: 'small'
						}
					}, [h('i', {
						attrs: {
							style: 'margin-right:5px;font-size:13px;',
							class: "el-icon-d-caret el-icon--left"
						}
					}), '排序']),
					h('el-button', {
						on: {
							click: this.rename(node.data)
						},
						attrs: {
							type: 'primary',
							size: 'small'
						}
					}, [h('i', {
						attrs: {
							style: 'margin-right:5px;font-size:13px;',
							class: "el-icon-edit el-icon--left"
						}
					}), '编辑']),
					// h('el-button', {
					// 	on: {
					// 		click: this.bindLocation(node.data)
					// 	},
					// 	attrs: {
					// 		type: 'primary',
					// 		size: 'small'
					// 	}
					// }, [h('i', {
					// 	attrs: {
					// 		style: 'margin-right:5px;font-size:13px;',
					// 		class: "el-icon-eleg-icon_link el-icon--left"
					// 	}
					// }), '绑定馆藏地'])
					])
					]);
				} else {
					return h('span', {
						attrs: {
							class: "clearfloat",
							style: 'width:100%;display:inline-block'
						}
					}, [h('i', {
						attrs: {
							class: ""
						}
					}),
					node.data.Name,

					h('span', {
						attrs: {
							style: 'float:right;text-align:right;margin-right:60px'
						}
					}, [
					h('el-button', {
						on: {
							click: this.appendit(node.data)
						},
						attrs: {
							type: 'primary',
							size: 'small'
						}
					}, [h('i', {
						attrs: {
							style: 'margin-right:5px;font-size:13px;',
							class: "el-icon-plus el-icon--left"
						}
					}), '添加']),
					h('el-button', {
						on: {
							click: this.rename(node.data)
						},
						attrs: {
							type: 'primary',
							size: 'small'
						}
					}, [h('i', {
						attrs: {
							style: 'margin-right:5px;font-size:13px;',
							class: "el-icon-edit el-icon--left"
						}
					}), '编辑']),
					// h('el-button', {
					// 	on: {
					// 		click: this.bindLocation(node.data)
					// 	},
					// 	attrs: {
					// 		type: 'primary',
					// 		size: 'small'
					// 	}
					// }, [h('i', {
					// 	attrs: {
					// 		style: 'margin-right:5px;font-size:13px;',
					// 		class: "el-icon-eleg-icon_link el-icon--left"
					// 	}
					// }), '绑定馆藏地'])
					]),
					]);
				}
			},
			//添加主区域
			createArea() {
				this.typeShow = true;
				this.parentAreaNameShow = false;
				this.createAreaDialog = true;
				this.createForm.parentkeyid = '';
				this.createForm.level = 1;
			},
			//提交添加区域
			confirmCreateArea(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						var param = {
							name: this.createForm.areaName,
							type: this.createForm.type,
							level: this.createForm.level,
							sortnumber: this.sortNumber,
							creator: GloabFun.getUid(),
							parentkeyid: this.createForm.parentkeyid
						}
						// console.log('创建区域', param);
						HttpServer.httpPost.call(this, '/Api/District/Create', param, function(response) {}, function(response) {
							console.log('添加主区域返回', response)
							if(response.data.code === 0) {
								this.defaultKey.splice(0, this.defaultKey.length);
								this.getDatas();
								this.createAreaDialog = false;
								this.$notify({
									title: '成功',
									message: this.$t('message.addSuccess'),
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				});
			},
			//主区域排序
			sortArea() {
				this.sortAreaDialog = true;
				this.sortAreas = this.tableData;
			},
			//子区域排序
			editit(node) {
				return function() {
					this.sortAreaDialog = true;
					this.sortAreas = node.Children;
				}.bind(this)
			},
			//确认排序
			confirmSortArea() {
				var newSortArea = [];
				for(var i = 0; i < this.sortAreas.length; i++) {
					newSortArea[i] = {};
					newSortArea[i].name = this.sortAreas[i].Name;
					newSortArea[i].keyid = this.sortAreas[i].DistrictKeyId;
					newSortArea[i].sortnumber = i + 1;
				}
				// console.log('newSortArea',newSortArea);
				HttpServer.httpPost.call(this, '/Api/District/Update', {
					info: newSortArea
				}, function(response) {}, function(response) {
					// console.log('排序结果',response);
					if(response.data.code === 0) {
						this.defaultKey.splice(0, this.defaultKey.length);
						this.getDatas();
						this.sortAreaDialog = false;
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			//批量删除
			deleteArea() {
				// console.log('this.$refs.tree.getCheckedNodes()',this.$refs.tree.getCheckedNodes());
				if(this.$refs.tree.getCheckedNodes().length > 0) {
					this.$confirm('此操作将删除区域信息，是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						var keyids = [];
						for(var i = 0; i < this.$refs.tree.getCheckedNodes().length; i++) {
							// keyids[i] = {};
							keyids.push(this.$refs.tree.getCheckedNodes()[i].DistrictKeyId);
						}
						HttpServer.httpPost.call(this, '/Api/District/Delete', {
							keyid: keyids
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.getDatas();
								this.$notify({
									title: '成功',
									message: this.$t('message.bulkDeleteSuccess'),
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.cancleOperation'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: this.$t('message.selectBulkDeleteWarning'),
						type: 'warning',
						duration: 2500
					});
				}
			},
			//创建子区域
			appendit(node) {
				return function() {
					this.typeShow = false;
					this.createAreaDialog = true;
					this.parentAreaNameShow = true;
					this.createForm.parentAreaName = node.Name;
					this.sortNumber = node.Children.length + 1;
					this.createForm.parentkeyid = node.DistrictKeyId;
					this.createForm.level = node.Level + 1;
				}.bind(this);
			},
			// 重命名
			rename(node) {
				return function() {
					this.renameDistrictForm.creator = node.Creator;
					this.renameDistrictForm.time = node.Time;
					this.renameDistrictForm.updateTime = node.UpdateTime;
					this.renameDistrictForm.areaName = node.Name;
					this.renameDistrictForm.keyid = node.DistrictKeyId;
					this.renameDistrictForm.sortNumber = node.SortNumber;
					this.renameAreaDialog = true;
				}.bind(this)
			},
			//确定重命名
			confirmRename(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						var info = [{
							keyid: this.renameDistrictForm.keyid,
							sortnumber: this.renameDistrictForm.sortNumber,
							name: this.renameDistrictForm.areaName
						}]
						HttpServer.httpPost.call(this, '/Api/District/UpdateName', {
							info: info
						}, function(response) {}, function(response) {
							// console.log('修改区域', response)
							if(response.data.code === 0) {
								this.defaultKey.splice(0, this.defaultKey.length);
								this.getDatas();
								this.renameAreaDialog = false;
								this.$notify({
									title: '成功',
									message: this.$t('message.saveSuccess'),
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					} else {
						return false;
					}
				});
			},
			//绑定馆藏地
			bindLocation(node) {
				return function() {
					this.bindDistrictrInfo = node;
					this.getAllLocationDatas();
					this.locationDialog = true;
				}.bind(this)
			},
			//去掉时间中的T
			formateData(array) {
				for(var i = 0; i < array.length; i++) {
					var index1 = array[i].CreateTime.indexOf("T");
					var index2 = array[i].UpdateTime.indexOf("T");
					array[i].CreateTime = array[i].CreateTime.substring(0, index1) + " " + array[i].CreateTime.substring(index1 + 1, index1 + 9);
					array[i].UpdateTime = array[i].UpdateTime.substring(0, index2) + " " + array[i].UpdateTime.substring(index2 + 1, index2 + 9);
				}
			},
			getAllLocationDatas() {
				this.loading = true;
				HttpServer.httpPost.call(this, '/Api/LibraryLocation/List', {
					UserId: parseInt(GloabFun.getKeyId()),
					index: this.currentPage,
					pagesize: this.pageSize,
					districtid: 0,
					keyword: ''
				}, function(response) {}, function(response) {
					this.loading = false;
					if(response.data.code === 0) {
						this.formateData(response.data.info);
						this.locationDatas = response.data.info;
						this.totalSize = response.data.total;
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getAllLocationDatas();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.getAllLocationDatas();
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			formateSelection() {
				var result = [],
				array = this.multipleSelection;
				for(var i = 0; i < array.length; i++) {
					result.push(array[i].LocationKeyId);
				}
				return result;
			},
			//确认绑定馆藏地
			confirmBindLocation() {
				if(this.formateSelection().length === 0){
					this.$notify({
						title: this.$t('message.warning'),
						message: '请选择批量操作的项',
						type: 'warning',
						duration: 2500
					});
				}else {
					this.$confirm('此操作将所选馆藏地绑定至区域'+ this.bindDistrictrInfo.Name +'，是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						HttpServer.httpPost.call(this, '/Api/District/Bind/Location', {
							locationids: this.formateSelection(),
							districtid: this.bindDistrictrInfo.DistrictKeyId,
							UserId: parseInt(GloabFun.getKeyId())
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.$notify({
									title: '成功',
									message: '绑定成功',
									type: 'success',
									duration: 2500
								});
								this.getDatas();
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.operationCanceled'),
							duration: 2500
						})
					});
				}
			},
			//刷新
			reloadDatas() {
				this.isReload = true;
				this.getDatas();
			},
			//处理数据中的时间
			formateDataTime(arr) {
				for (var m = 0 ; m < arr.length; m ++){
					var index1 = arr[m].Time.indexOf("T");
					var index2 = arr[m].UpdateTime.indexOf("T");
					arr[m].Time = arr[m].Time.substring(0, index1) + " " + arr[m].Time.substring(index1 + 1, index1 + 9);
					arr[m].UpdateTime = arr[m].UpdateTime.substring(0, index2) + " " + arr[m].UpdateTime.substring(index2 + 1, index2 + 9);
					if(arr[m].Children && arr[m].Children.length > 0){
						this.formateDataTime(arr[m].Children);
					}
				}
			},
			getDatas() {
				this.loading = true;
				this.defaultKey.splice(0, this.defaultKey.length);
				HttpServer.httpPost.call(this, '/Api/District/info', {
					keyids: []
				}, function(response) {}, function(response) {
					this.loading = false;
					// console.log(response)
					if(response.data.code === 0) {
						if(response.data.info) {
							this.sortNumber = response.data.info.length + 1; //排序序号（主区域）
							this.formateDataTime(response.data.info);
							this.tableData = response.data.info;
							this.sortAreas = response.data.info;
							this.defaultKey.push(this.tableData[0].DistrictKeyId);
							if(this.isReload){
								this.$notify({
									title: '成功',
									message: this.$t('message.refreshSuccess'),
									type: 'success',
									duration: 2500
								});
							}
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
					this.isReload = false;
				});
			}
		},
		created() {
			this.getDatas();
		}
	}
</script>

<style>
	.district-tree .el-tree-node__children {
		width: 100%;
	}
</style>
<style scoped lang="less">
	.color-item {
		border: none;
		color: #fff;
		text-shadow: 1px 1px 0 rgba(0, 0, 0, .5);
		cursor: move;
		text-align: center;
		height: 25px;
		-webkit-border-radius: 5px;
		-moz-border-radius: 5px;
		border-radius: 5px;
		margin: 5px 20px;
		display: block;
		background: #4a5e6f;
		text-align: center;
		line-height: 25px;
		// box-shadow:inset 0 1px 0 #617586,inset 0 0 40px 5px rgba(0,0,0,.3),0 0 2px 1px rgba(0,0,0,.5);
	}
	
	.color-item:hover {
		position: relative;
		top: 1px;
		box-shadow: inset 0 -1px 0 #617586, inset 0 2px 8px rgba(0, 0, 0, .5), inset 0 0 40px 5px rgba(0, 0, 0, .25)/*,0 0 2px 1px rgba(0,0,0,.5)*/
		;
		color: #fff;
	}
	
	.table-icon {
		color: #20a0ff;
		font-size: 20px;
		font-weight: bold;
		padding: 5px 0;
	}
</style>